package com.qiyuexinxi.chat.util;

import com.qiyuexinxi.chat.service.impl.LoginServiceImpl;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.Random;


public class PictureUtil {
	
	/**
	 * 文件名格式 ：/年/月/日/时分秒+随机数.文件后缀
	 * @param appImage
	 * @param filePath
	 * @param domainNameAddresses
	 * @return
	 */
	public static String fileUpload(MultipartFile appImage, String filePath, String domainNameAddresses) {
        // 文件名
		String fileName = appImage.getOriginalFilename();
        // 后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        //获取当前时间的年月日
        int year =Calendar.getInstance().get(Calendar.YEAR);
        int month = Calendar.getInstance().get(Calendar.MONTH)+1;
        int day = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
        int hour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
        int minute = Calendar.getInstance().get(Calendar.MINUTE);
        int second = Calendar.getInstance().get(Calendar.SECOND);
        Random random = new Random();
		int ends = random.nextInt(99);
        // 新文件名
        fileName = ""+hour + minute + second + String.format("%02d",ends) + suffixName;
        String filePathNew = filePath + year+File.separator+month+File.separator+day;
        File destFile = new File(filePathNew);
        if(!destFile.exists()) {
        	destFile.mkdir();
        }
        File dest = new File(filePathNew + File.separator + fileName);
        // 检测是否存在目录
        if (!dest.getParentFile().exists()) {
            //假如文件不存在即重新创建新的文件已防止异常发生
            dest.getParentFile().mkdirs();
        }
        try {
        	appImage.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
        }
		return domainNameAddresses+year+File.separator+month+File.separator+day+File.separator+fileName;
	}
}
